package com.examination.system.administrator.service.impl;

import com.examination.framework.exception.ExceptionCast;
import com.examination.framework.model.response.CommonCode;
import com.examination.framework.model.response.ResponseResult;
import com.examination.system.administration.CollegeMajorClassification;
import com.examination.system.administration.ext.CollegeMajorClassificationNode;
import com.examination.system.administration.response.AddAdministrationResult;
import com.examination.system.administration.response.AdministrationCode;
import com.examination.system.administration.response.DeleteAdministrationResult;
import com.examination.system.administrator.dao.CqeecExaminationSystemMapper;
import com.examination.system.administrator.dao.CqeecExaminationSystemRepository;
import com.examination.system.administrator.service.CollegeMajorClassificationService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Transient;
import java.util.*;

/**
 * @author 寇淇芮
 * @Date 2019/8/20 15:40
 */
@Service
public class CollegeMajorClassificationServiceImpl implements CollegeMajorClassificationService {
    /**
     * 顶级父节点
     */
    @Value("${collegeMajorClassification.topPlate}")
    private String collegeMajorClassificationTopPlate;

    @Autowired
    CqeecExaminationSystemMapper cqeecExaminationSystemMapper;
    @Autowired
    CqeecExaminationSystemRepository cqeecExaminationSystemRepository;

    /**
     * 添加数据
     * @param id
     * @param collegeMajorClassification
     * @return
     */
    @Override
    @Transient
    @Transactional
    public AddAdministrationResult addCollegeMajorClassification(String id, CollegeMajorClassification collegeMajorClassification) {
        /*
        判断id是否为空,
        判断collegeMajorClassification是否传入数据
        判断name是否为"" 建议去前后空格
         */
        if(StringUtils.isEmpty(id)||collegeMajorClassification==null||collegeMajorClassification.getName().trim().equals("")){
            ExceptionCast.cast(AdministrationCode.ADMINISTRATION_PARAMETER);
        }
        //查询是否同名
        if( cqeecExaminationSystemMapper.findByName(id,collegeMajorClassification.getName()).size()>0){
            ExceptionCast.cast(AdministrationCode.COLLEGEMAJORCLASSIFICATIONADDNAME);
        }
        //查询父目录
        CollegeMajorClassification plateNode = getCollegeMajorClassificationById(id);
        if(plateNode==null){
            ExceptionCast.cast(AdministrationCode.ERRNODE);
        }
        //如果不是父目录修改数据
        if(plateNode.getCatalogue().equals("0")){
            plateNode.setCatalogue("1");
            cqeecExaminationSystemRepository.save(plateNode);
        }
        CollegeMajorClassification newNode = new CollegeMajorClassification();
        //排序
        int rank = cqeecExaminationSystemRepository.findByPlate(id).size()+1;
        //填写数据
        newNode.setId(UUID.randomUUID().toString());
        newNode.setPlate(id);
        newNode.setName(collegeMajorClassification.getName());
        newNode.setCatalogue("0");
        newNode.setRank(rank);
        newNode.setCreationTime(new Date());
        newNode.setUpdateTime(new Date());
        //保存数据
        CollegeMajorClassification save = cqeecExaminationSystemRepository.save(newNode);
        return new AddAdministrationResult(AdministrationCode.SUCCESS,save.getId());
    }
    /**
     * 根据id删除数据
     * @param id
     * @return
     */
    @Override
    @Transient
    @Transactional //开启事务
    public DeleteAdministrationResult removeCollegeMajorClassification(String id){

        if(StringUtils.isEmpty(id)){
            ExceptionCast.cast(AdministrationCode.ADMINISTRATION_PARAMETER);
        }
        //先查出单条数据
        CollegeMajorClassification collegeMajorClassification = this.getCollegeMajorClassificationById(id);
        if(collegeMajorClassification.getPlate().equals(collegeMajorClassificationTopPlate)){
            ExceptionCast.cast(AdministrationCode.COLLEGEMAJORCLASSIFICATIONTOPPLATE);
        }
        //根据父id查询该节点是否还有数据
        List<CollegeMajorClassification>  plateList = cqeecExaminationSystemRepository.findByPlate(collegeMajorClassification.getPlate());
        if(plateList!=null&&plateList.size()==1){
            //查出父节点
            CollegeMajorClassification plateNode = this.getCollegeMajorClassificationById(collegeMajorClassification.getPlate());
            //改变父节点的Catalogue值
            plateNode.setCatalogue("0");
            //保存
            cqeecExaminationSystemRepository.save(plateNode);
        }
        //判断是否是父节点
        if(collegeMajorClassification.getCatalogue().equals("0")){
            //删除该节点
            return cqeecExaminationSystemMapper.deleteById(id) != 1?new DeleteAdministrationResult(AdministrationCode.FAIL,id):new DeleteAdministrationResult(AdministrationCode.SUCCESS,id);

        }
        //如果是根结点
        if (this.removeNode(id)){
            return cqeecExaminationSystemMapper.deleteById(id) != 1?new DeleteAdministrationResult(AdministrationCode.FAIL,id):new DeleteAdministrationResult(AdministrationCode.SUCCESS,id);
        }
        return  new DeleteAdministrationResult(AdministrationCode.FAIL,id);
    }



    /**
     * 根据父节点的id删除所有的子节点
     * @param id
     * @return
     */
    private Boolean removeNode(String id) {
        //先查节点
        CollegeMajorClassification one = this.getCollegeMajorClassificationById(id);
        //在查子节点
        List<CollegeMajorClassification> nodeList = cqeecExaminationSystemRepository.findByPlate(one.getId());
        if(nodeList==null){
            ExceptionCast.cast(AdministrationCode.ERRNODE);
        }
        //遍历数据
        for(CollegeMajorClassification node :nodeList){
            if(node.getCatalogue().equals("1")){
                removeNode(node.getId());
            }
           if(cqeecExaminationSystemMapper.deleteById(node.getId())==0){
               ExceptionCast.cast(AdministrationCode.FAIL);
           };
        }
        return true;
    }

    /**
     * 根据id修改数据
     * @param id
     * @param collegeMajorClassification
     * @return
     */
    @Override
    public ResponseResult editCollegeMajorClassificationById(String id, CollegeMajorClassification collegeMajorClassification) {
        CollegeMajorClassification one =  this.getCollegeMajorClassificationById(id);
        if(one == null){
            ExceptionCast.cast(AdministrationCode.ADMINISTRATION_PARAMETER);
        }
        one.setName(collegeMajorClassification.getName());
        one.setUpdateTime(new Date());
        CollegeMajorClassification save = cqeecExaminationSystemRepository.save(one);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /**
     * 根据id获取单个数据
     * @param id
     * @return
     */
    private CollegeMajorClassification getCollegeMajorClassificationById(String id) {
        Optional<CollegeMajorClassification> optional = cqeecExaminationSystemRepository.findById(id);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    /**
     * 返回数据
     * @return
     */
    @Override
    public List<CollegeMajorClassificationNode> findCollegeMajorClassificationList() {
        List<CollegeMajorClassification> nodeLists = cqeecExaminationSystemRepository.findAll();
        return mergeMajorClassificationNode(nodeLists,"001");
    }

    /**
     * 利用递归的方式遍历数据,形成数
     * @param nodeList
     * @param plate
     * @return
     */
    private List<CollegeMajorClassificationNode> mergeMajorClassificationNode(List<CollegeMajorClassification> nodeList,String plate) {
        List<CollegeMajorClassificationNode>  collegeMajorClassificationNode = new ArrayList<>();
        for (CollegeMajorClassification node : nodeList ) {
            CollegeMajorClassificationNode children = new CollegeMajorClassificationNode();
            if(node.getPlate().equals(plate)){
                children.setId(node.getId());
                children.setName(node.getName());
                children.setPlate(node.getPlate());
                children.setRank(node.getRank());
                children.setCreationTime(node.getCreationTime());
                children.setUpdateTime(node.getUpdateTime());
                children.setChildren(mergeMajorClassificationNode(nodeList,node.getId()));
                collegeMajorClassificationNode.add(children);
            }
        }
        return  collegeMajorClassificationNode;
    }


}
